package com.zlsf.verticles;

import cn.hutool.core.util.StrUtil;
import com.zlsf.conf.Config;
import com.zlsf.entity.Media;
import com.zlsf.publish.Subscribermanager;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * http服务
 */
@Slf4j
public class WebVerticle extends AbstractVerticle {
  @Override
  public void start() throws Exception {
    super.start();
    int port = Config.getInstance().getConfig().getJsonObject("http").getInteger("port", 8080);
    this.createHttpServer(port);
  }

  private void createHttpServer(int port) {
    // 创建HttpServer
    HttpServer server = vertx.createHttpServer();
    // 创建路由对象
    Router router = Router.router(vertx);
    // 监听/index地址
    router.route("/video").blockingHandler(this::handleVideo);
    server.requestHandler(router);
    server.listen(port).onSuccess(http -> log.info("http服务器启动成功，端口号：{}", port));
  }

  /**
   * 处理视频的请求
   *
   * @param ctx
   */
  private void handleVideo(RoutingContext ctx) {

    String tag = ctx.request().getParam("tag");
    if (StrUtil.isEmpty(tag)) {
      ctx.response().setStatusCode(500).setStatusMessage("参数【tag】不能为空").end();
      return;
    }
    ctx.response()
      .putHeader("Connection", "keep-alive")
      .putHeader("Content-Type", "video/x-flv")
      .putHeader("Transfer-Encoding", "chunked")
      .putHeader("Cache-Control", "no-cache")
      .putHeader("Access-Control-Allow-Origin", "*")
      .putHeader("Access-Control-Allow-Credentials", "true")
      .setChunked(true)
      .closeHandler(v -> {
        // 客户端断开连接时的处理
        Subscribermanager.getInstance().unsubscribe(tag, ctx);
        ctx.response().end();
      });

    ctx.response().write("");
    Subscribermanager.getInstance().subscribe(tag, ctx, Media.Type.Video, vertx);
  }
}
